package com.example.data.factory.service.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.data.factory.common.Dto.InsertDictDto;
import com.example.data.factory.common.result.R;
import com.example.data.factory.entity.entity.DictData;
import com.example.data.factory.mapper.mapper.DictDataMapper;
import com.example.data.factory.service.service.DictDataService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhy
 * @since 2025-03-03
 */
@Service
public class DictDataServiceImpl extends ServiceImpl<DictDataMapper, DictData> implements DictDataService {
    private final RestTemplate restTemplate;
    private final String addUrl = "http://localhost:8080/dict/InsertDict";

    public DictDataServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    public void saveDictData(InsertDictDto insertDictDto) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        HttpEntity<InsertDictDto> request = new HttpEntity<>(insertDictDto, headers);

        ResponseEntity<R> response = restTemplate.exchange(addUrl, HttpMethod.POST, request, R.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            R body = response.getBody();
            // 正确解析并打印错误信息
            String reason = body != null ? body.getMsg() : "未知原因";
            System.err.println("数据保存成功: " + insertDictDto.getDictName() + ", 原因: " + reason);
        } else {
            // 如果不是2xx响应，也打印状态码和响应体
            R body = response.getBody();
            String reason = body != null ? body.getMsg () : "未知原因";
            System.err.println("数据保存失败: " + insertDictDto.getDictName() + ", HTTP状态码: " + response.getStatusCodeValue() + ", 原因: " + reason);
        }
    }
}
